<?php

class CategoryLogic {

    private $query;

    public function __construct() {
        $this->query = DB::table('category');
    }

    public function getHieraCats($catID) {
        $ret = DB::query('SELECT parent.id, parent.name FROM category AS node,category AS parent WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = ? ORDER BY parent.lft', array($catID));
        if (!is_array($ret)) {
            return false;
        }
        $tmp = array_slice($ret, 1);
        return json_decode(json_encode($tmp), true);
    }

    public function addCategory($parent_id, $name) {

        $ret = DB::query("SELECT name FROM category WHERE id = ?;", $parent_id);
        if (empty($ret)) {
            return false;
        }

        try {
            DB::connection()->pdo->beginTransaction();
            DB::query("SELECT @myLeft := lft FROM category WHERE id = ?;", $parent_id);
            DB::query("UPDATE category SET rgt = rgt + 2 WHERE rgt > @myLeft;");
            DB::query("UPDATE category SET lft = lft + 2 WHERE lft > @myLeft;");
            DB::query("INSERT INTO category(parent_id,name, lft, rgt) VALUES(?, ?, @myLeft+ 1, @myLeft+ 2);", array($parent_id, $name));
            DB::connection()->pdo->commit();
            return true;
        } catch (PDOException $e) {
            DB::connection()->pdo->rollBack();
            return false;
        }
    }

    public function updateCategory($new_parent, $name) {
        if ($this->deleteCategory($name) === false)
            return False;
        $this->addCategory($new_parent, $name);
    }

    public function deleteCategory($id) {
        $ret = DB::query("SELECT name FROM category WHERE id = ?;", $id);
        if (empty($ret)) {
            return false;
        }

        try {
            DB::connection()->pdo->beginTransaction();
            DB::query(" SELECT @myLeft := lft, @myRight := rgt, @myWidth := rgt - lft + 1 FROM category WHERE id = ?;", $id);
            $ret = DB::query("SELECT id FROM category WHERE lft BETWEEN @myLeft AND @myRight;");
            foreach ($ret as $key => $value) {
                DB::query(" UPDATE video SET category_id=0 where category_id = ?", $value->id);
            }
            DB::query("DELETE FROM category WHERE lft BETWEEN @myLeft AND @myRight;");
            DB::query("UPDATE category SET rgt = rgt - @myWidth WHERE rgt > @myRight; ");
            DB::query("UPDATE category SET lft = lft - @myWidth WHERE lft > @myRight;");
            DB::connection()->pdo->commit();
            return true;
        } catch (PDOException $e) {
            DB::connection()->pdo->rollBack();
            return false;
        }
    }

    public function getParent($id) {
        
    }

    public function getChild($id) {
        return $this->query->where('parent_id', '=', $id)->get();
    }

    public function getCategory($id) {
        return $this->query->find($id);
    }

    public function listCategory() {
        return $this->query->get();
    }

    public function getBrolevelCats($catID) {
        $parentID = DB::table('category')->where('id', '=', $catID)->only('parent_id');
        $ret = DB::query('SELECT id,name FROM category WHERE parent_id = ?', array($parentID));
        if (!is_array($ret)) {
            return false;
        }
        $tmp = array_slice($ret, 1);
        return json_decode(json_encode($tmp), true);
    }

    public function getNextLevelCats($parent_id) {
        $ret = DB::table('category')->where('parent_id', '=', intval($parent_id))->get(array('id', 'name'));
        foreach ($ret as $key => $value) {
            if (0 == $value->id) {
                unset($ret[$key]);
                break;
            }
        }
        return $ret;
    }

    public function listTopLevelCats() {
        $ret = DB::query('SELECT node.id,node.name, (COUNT(parent.name) - 1) AS depth FROM category AS node,category AS parent
				WHERE node.lft BETWEEN parent.lft AND parent.rgt
				GROUP BY node.name
				ORDER BY node.lft;');
        if (!is_array($ret)) {
            return false;
        }
        $topLevelIDarr = array();
        foreach ($ret as $key => $value) {
            if (1 == $value->depth && 0 != $value->id) {
                $topLevelIDarr[] = array(
                    $value->id,
                    $value->name
                );
            }
        }
        if (empty($topLevelIDarr)) {
            return false;
        }
        return $topLevelIDarr;
    }

    public function getSchedulePageCatlist() {
        $topCats = $this->listTopLevelCats();
        if (false === $topCats) {
            return false;
        }

        foreach ($topCats as $key => $value) {
            $sonList = $this->getNextLevelCats($value[0]);
            $topCats[$key][] = json_decode(json_encode($sonList), true);
        }
        return $topCats;
    }
    
    public function getHomepageProductList() {
        $topLevelCatIDArr = $this->listTopLevelCats();
        if (empty($topLevelCatIDArr)) {
            return false;
        }
        $videLogic = new VideoLogic();
        $homeVideoList = array();
        foreach ($topLevelCatIDArr as $item) {
            $catID = $item[0]; //id
            $catName = $item[1]; //name
            $catArr = DB::query('SELECT node.id, node.name FROM category AS node, category AS parent, category AS sub_parent
                WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
                AND sub_parent.id=' . $catID . ' GROUP BY node.name ORDER BY node.lft');
            //dd($catArr);
            $idArr = array();
            foreach ($catArr as $item) {
                $idArr[] = $item->id;
            }
            $list = $videLogic->getFixedVideoListByCatIDArr($idArr);
            $homeVideoList[] = array(
                $catID,
                $catName,
                json_decode(json_encode($list), true),
            );
        }
        return $homeVideoList;
    }

    public function listCategoryTree() {
        //$rootRow = $this->query->find(0);
        $rootRow = DB::query('select lft, rgt from category where id = 0');
        $lft = $rootRow[0]->lft;
        $rgt = $rootRow[0]->rgt;
        $item = DB::query('SELECT id, name, lft, rgt FROM category WHERE lft BETWEEN ? AND ? ORDER BY lft ASC;
            ', array($lft, $rgt));
        $retArr = json_decode(json_encode($item), true);
        $ret = $this->createTree($retArr);
        return $ret;
    }

    private function createTree($dataSet) {
        //echo 1;
        $rgt = 0;
        $tree = array_shift($dataSet);

        if ($tree['lft'] + 1 == $tree['rgt'])
            $tree['leaf'] = true;
        else {
            foreach ($dataSet as $key => $item) {
                //not a child
                if ($item['lft'] > $tree['rgt'])
                    break;
                //not a top-level child
                if ($rgt > $item['lft'])
                    continue;
                $tree['children'][] = $this->createTree($dataSet);

                foreach ($dataSet as $childKey => $childItem) {
                    if ($childItem['rgt'] < $item['rgt'])
                        unset($dataSet[$childKey]);
                }

                $rgt = $item['rgt'];

                unset($dataSet[$key]);
            }
        }

        unset($tree['lft'], $tree['rgt']);
        return $tree;
    }

}
?>

